<?php

    namespace lactone\Core\network;
    use lactone\Core\Object;

    /**
     * 客户端网络链接工具
     * 支持长链接
     * 支持异步
     * Class ClientInstance
     */
    class ClientInstance extends Object{
        public $ip;
        public $port;

        protected $ClientTool;
        public $isConnect = false;

        public function initClient($isAsync = false,$type=SWOOLE_SOCK_TCP){

            $this->log("Connect to ".$this->ip.":".$this->port);

            if(!$this->ip || !$this->port) return false;

            if(!$isAsync){
                $this->ClientTool = new \swoole_client($type);
                if(!$this->ClientTool->connect($this->ip,$this->port,-1)){
                    $this->log("Connect Faild:".$this->ClientTool->errCode);
                    return false;
                }
            }else{
                $this->ClientTool = new \swoole_client($type,SWOOLE_SOCK_ASYNC);
                foreach(['Connect','Receive','Error','Close'] as $Event){
                    $EventName = "on".$Event;
                    $this->ClientTool->on($Event,array($this,$EventName));
                }

                $this->ClientTool->connect($this->ip,$this->port);
            }

            $this->isConnect = true;

            return true;
        }

        /**
         * 发送数据
         * @param $data
         * @return mixed
         */
        public function Send($data){

            \Lactone::debug($this->logMessage($data,'ClientSend'));

            return $this->ClientTool->send($data.\Lactone::SOCKET_TAG);
        }

        /**
         * 获取数据,方法会阻塞
         * @return mixed
         */
        public function recv(){
            return $this->ClientTool->recv();
        }

        public function onConnect(swoole_client $cli){
            \Lactone::debug($this->logMessage("Client Connect!",'ClientSend'));
        }

        public function onReceive(swoole_client $cli, $data){

            \Lactone::debug($this->logMessage("Receive data!",'ClientSend'));
        }

        public function onError(swoole_client $cli){
            \Lactone::debug($this->logMessage("Connect Error!",'ClientSend'));
        }

        public function onClose(swoole_client $cli){
            \Lactone::debug($this->logMessage("Connect Close!",'ClientSend'));
        }

    }